package com.ok.common.utils

import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.view.MotionEvent

object ActivityTimeoutUtils {

    private var DEFAULT_TIMEOUT_MS = 2 * 60 * 1000L // 默认超时时间为2分钟
    private val handler = Handler()
    private var runnable: Runnable? = null

    fun setTimeout(activity: Activity, timeoutMs: Long = DEFAULT_TIMEOUT_MS, targetActivity: Class<*>) {

        cancelTimeout()

        runnable = Runnable {
            val intent = Intent(activity, targetActivity)
            intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
            activity.startActivity(intent)
            activity.finish()
        }

        resetTimer(timeoutMs)

    }

    private fun resetTimer(timeoutMs: Long = DEFAULT_TIMEOUT_MS) {
        runnable?.let {
            handler.removeCallbacks(it)
            handler.postDelayed(it, timeoutMs)
        }

    }

    fun cancelTimeout() {
        runnable?.let {
            handler.removeCallbacks(it)
        }
    }

    fun onTouchEvent(event: MotionEvent) {
        resetTimer()
    }
}
